package com.example.debangfix.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.debangfix.bean.BathUpdateDo;
import com.google.common.collect.Lists;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.apache.commons.io.FileUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class FixUserMonthBillService {

    private static String jsonPath = "C:\\Users\\ayyk\\Desktop\\totalRecord.json";
//    private static String jsonPath = "D:\\past-job\\totalRecord.json";

    @Autowired
    private MongoTemplate mongoTemplate;

    private static volatile int updateCount = 0;


    public void fixUserMonthBill() throws IOException, InterruptedException {
        List<BathUpdateDo> paramList = new ArrayList<>();
        String jsonStr = FileUtils.readFileToString(new File(jsonPath));
        JSONArray jsonObject = JSON.parseObject(jsonStr).getJSONArray("RECORDS");
        System.out.println("总共有" + jsonObject.size() + "条数据");
        jsonObject.stream().forEach(item -> {
            JSONObject userJson = (JSONObject) item;
            String billUserId = userJson.getString("billUserId");
            long durationOfMinute = userJson.getLongValue("durationOfMinute");
            long duration = userJson.getLongValue("duration");
//            5d7f844aec5ea16c3e352f5b  5d6857e1aeee106618e806d6
            Query query = Query.query(Criteria.where("userId").is(billUserId).and("monthSetId").is("5d6857e1aeee106618e806d6"));
            Update update = new Update().set("totalDuration", duration).set("totalDurationOfMinute", durationOfMinute);
            BathUpdateDo bathUpdateDo = new BathUpdateDo(query, update);
            paramList.add(bathUpdateDo);
        });

        final CountDownLatch countDownLatch = new CountDownLatch(18);

        List<List<BathUpdateDo>> partition = Lists.partition(paramList, 1000);

        ExecutorService executorService = Executors.newFixedThreadPool(18);


        partition.stream().forEach(item -> {

            executorService.execute(() -> {
                doBathUpdate("ucUserMonthBill", item);
                countDownLatch.countDown();
            });

        });

        countDownLatch.await();

        System.out.println(updateCount+"条数据更新成功");
    }

    public int doBathUpdate(String collectionName, List<BathUpdateDo> paramList) {

        DBObject command = new BasicDBObject();

        command.put("update", collectionName);

        List<BasicDBObject> updateList = new ArrayList<BasicDBObject>();

        for (BathUpdateDo bathUpdateDo : paramList) {
            BasicDBObject update = new BasicDBObject();
            update.put("q", bathUpdateDo.getQuery().getQueryObject());
            update.put("u", bathUpdateDo.getUpdate().getUpdateObject());
            updateList.add(update);
        }

        command.put("updates", updateList);

        Document document = mongoTemplate.getDb().runCommand((Bson) command);
        Object n = document.get("n");

        if (n.getClass() == Integer.class) {
            updateCount += (Integer) n;
            return (Integer) n;
        }
        updateCount += Integer.parseInt(String.valueOf(n));

        return Integer.parseInt(String.valueOf(n));

    }

}
